package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.customer.mapper.WaarmerkMapper;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.service.IWaarmerkService;
import com.jzo2o.customer.service.IWorkerCertificationAuditService;
import com.jzo2o.mvc.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 01 7月 2025 19:47
 */
@Slf4j
@Service
public class WaarmerkServiceImpl extends ServiceImpl<WaarmerkMapper, WorkerCertification> implements IWaarmerkService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IWorkerCertificationAuditService workerCertificationAuditService;

    /**
     * 服务人员认证申请
     *
     * @param dto
     */
    @Override
    public void workerCertificationAudit(WorkerCertificationAuditAddReqDTO dto) {

        // 根据身份证号查询是否已存在认证记录
        WorkerCertificationAudit existingCertification = workerCertificationAuditService.lambdaQuery()
                .eq(WorkerCertificationAudit::getIdCardNo, dto.getIdCardNo())
                .one();

        // 检查现有认证状态
        if (existingCertification != null) {
            int status = existingCertification.getCertificationStatus();
            if (status == 2) {
                throw new CommonException("当前服务人员已认证，无需重复申请");
            }
            if (status == 1) {
                throw new CommonException("认证申请正在处理中，请耐心等待");
            }
            if (status == 3) {
                // 处理已拒绝的情况 - 删除旧记录
                workerCertificationAuditService.removeById(existingCertification.getId());
            }
        }

        // 创建新的认证申请
        WorkerCertificationAudit newCertification = new WorkerCertificationAudit();
        BeanUtils.copyProperties(dto, newCertification);

        // 设置申请人ID和默认状态
        newCertification.setServeProviderId(UserContext.currentUserId());
        newCertification.setCertificationStatus(1); // 认证中
        newCertification.setAuditStatus(1);

        // 保存新申请
        boolean success = workerCertificationAuditService.save(newCertification);
        if (!success) {
            throw new CommonException("提交认证申请失败");
        }
    }


    /**
     * 获取最新的驳回原因
     *
     * @return
     */
    @Override
    public Map<String, String> rejectReason() {
        // 查询最新的认证记录，使用标准分页方法替代last()
        Long workId = UserContext.currentUserId();
        WorkerCertificationAudit latestRecord = workerCertificationAuditService.lambdaQuery()
                .eq(WorkerCertificationAudit::getServeProviderId, workId)
                .orderByDesc(WorkerCertificationAudit::getAuditTime)
                .last("LIMIT 1") // 注意：确保数据库方言兼容LIMIT语法
                .one();

        // 检查记录是否存在或状态是否为未申请
        if (latestRecord == null || latestRecord.getCertificationStatus() == 0) {
            throw new CommonException("请先提交认证申请");
        }

        // 检查认证状态
        int status = latestRecord.getCertificationStatus();
        switch (status) {
            case 1:
                throw new CommonException("认证申请正在审核中，请耐心等待");
            case 2:
                throw new CommonException("您已认证成功，无需查看驳回原因");
            case 3: // 假设状态3为"已驳回"
                // 确保驳回原因不为空
                String reason = Optional.ofNullable(latestRecord.getRejectReason())
                        .filter(StringUtils::isNotBlank)
                        .orElse("未指定驳回原因，请联系管理员");
                return Collections.singletonMap("rejectReason", reason);
            default:
                // 处理其他未知状态
                throw new CommonException("未知认证状态: " + status);
        }
    }
}